package com.heima.wemedia.controller.v1;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.IWmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Slf4j
@RestController
public class TestController {

    @Autowired
    private IWmSensitiveService sensitiveService;

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {

        //dataList是表中所有的数据
        //WmSensitive.class表中对应的对象类型
        EasyExcel.read(file.getInputStream(), WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            //sensitive就是表中的对象
            for (WmSensitive wmSensitive : dataList) {

                log.info("读取到一条数据{}", JSON.toJSONString(wmSensitive));

                //判断这个敏感词是否已经存在
                LambdaQueryWrapper<WmSensitive> lqw = Wrappers.lambdaQuery(WmSensitive.class);
                lqw.eq(WmSensitive::getSensitives, wmSensitive.getSensitives());
                WmSensitive one = sensitiveService.getOne(lqw);

                //不存在
                if (one == null) {
                    wmSensitive.setCreatedTime(new Date());
                    sensitiveService.save(wmSensitive);
                }
            }
        })).sheet().doRead();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {

        //文件下载：一个流两个头
        /*
            一个流：文件的输出流 outputStream
            两个头：1.文件的打开方式  2.文件的mime类型
         */
        //文件的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //以副本的形式打开（可下载）
        response.setHeader("content-disposition", "attachment;filename=Sensitive.xlsx");
        //设置文件类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        EasyExcel.write(outputStream,WmSensitive.class)
                .sheet("敏感词")   //对应表中的Sheet1
                .doWrite(() ->{
                    //查询要导出的数据
                    return sensitiveService.list();
                });
    }

}
